package com.zy.mc_module.ui.login;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ClipboardManager.OnPrimaryClipChangedListener;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.zy.mc_module.R;
import com.zy.mc_module.base.App;
import com.zy.mc_module.base.BaseActivity;
import com.zy.mc_module.common.Constant;
import com.zy.mc_module.common.RxBusCode;
import com.zy.mc_module.mvp.bean.UserBean;
import com.zy.mc_module.mvp.contract.LoginContract;
import com.zy.mc_module.mvp.presenter.LoginPresenter;
import com.zy.mc_module.ui.setting.setpay.SetPayActivity;
import com.zy.mc_module.utils.*;
import com.zy.mc_module.utils.sms.SmsBroadcastReceiver;
import com.zy.mc_module.utils.sms.SmsBroadcastReceiver.MessageListener;
import com.zy.mc_module.view.CountDownTextView;
import com.zy.mc_module.view.CustomHeadLayout;
import com.zy.mc_module.view.PhoneCode;
import com.zy.mc_module.view.PhoneCode.onInputComplete;
import com.zy.mc_module.utils.retrofit.error.ThdException;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @Date 19/3/16
 * @Author dq
 * 短信验证码
 */
public class VerCodeActivity extends BaseActivity<LoginContract.View, LoginPresenter> implements
        LoginContract.View, onInputComplete {

    @BindView(R.id.customhead)
    CustomHeadLayout customhead;
    @BindView(R.id.vercode_tel)
    TextView tv_tel;
    @BindView(R.id.vercode_get)
    CountDownTextView tv_getcode;
    @BindView(R.id.vercode_phonecode)
    PhoneCode phoneCode;

    private String title, tel, code, openid, unionid, wxname, wxhead;
    private String codeStr;//验证码字符
    private boolean isClipboardChanged = false;//判断粘贴板是否改变
    private SmsBroadcastReceiver mSMSBroadcastReceiver;
    private boolean isNew;

    @Override
    protected LoginPresenter createPresenter() {
        return new LoginPresenter();
    }

    @Override
    protected boolean isNeedRxBus() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_vercode;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        App.getInstance().addTmpActivity(this);
        StatusBarUtil.setImmersiveStatusBar(this);
        customhead.setLeftClickListener(view -> finish());
        tel = AppTools.getHasKeyS(this, "tel");
        openid = AppTools.getHasKeyS(this, "openid");
        unionid = AppTools.getHasKeyS(this, "unionid");
        wxname = AppTools.getHasKeyS(this, "wxname");
        wxhead = AppTools.getHasKeyS(this, "wxhead");
        title = AppTools.getHasKeyS(this, "title");
        isNew = getIntent().getBooleanExtra("isNew", false);
        initData();

    }

    private void initData() {
        customhead.setText(title);
        tv_tel.setText("验证码已发送至 +86 " + StringsUtils.hideTel(tel));
        //验证码输入框监听事件
        phoneCode.setOnInputComplete(this);
        if (title.equals("短信验证")) {
            //找回支付密码
            presenter.getCode(context, "10", tel);
        } else {
            //获取验证码成功,倒计时
            countDown();
        }

        getPasteString();

        addMSGListener();
    }

    //添加短信息监听
    private void addMSGListener() {
        AndPermission.with(this).runtime().permission(Permission.READ_SMS, Permission.RECEIVE_SMS).onGranted(permissions -> {
            //开启了权限
            ((Activity) context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //实例化IntentFilter对象
                    IntentFilter filter = new IntentFilter();
                    filter.addAction("android.provider.Telephony.SMS_RECEIVED");
                    filter.setPriority(1000);
                    mSMSBroadcastReceiver = new SmsBroadcastReceiver();
                    //注册广播接收
                    registerReceiver(mSMSBroadcastReceiver, filter);
                    mSMSBroadcastReceiver.setOnReceivedMessageListener(new MessageListener() {

                        public void OnReceived(String message) {
                            String codeStr = StringsUtils.getCode(message);//截取6位验证码
                            if (!StringsUtils.isEmpty(codeStr)) {
                                phoneCode.clear();
                                phoneCode.setCode(codeStr);
                            }
                        }
                    });
                }
            });
        }).onDenied(permissions -> {
        }).start();
    }

    // 从黏贴板获取数据
    private void getPasteString() {
        // 获取并保存粘贴板里的内容
        ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.addPrimaryClipChangedListener(new OnPrimaryClipChangedListener() {
            @Override
            public void onPrimaryClipChanged() {
                ClipData clipData = clipboard.getPrimaryClip();
                if (clipData != null && clipData.getItemCount() > 0) {
                    CharSequence text = clipData.getItemAt(0).getText();
                    if (text != null) {
                        String clipString = text.toString();
                        codeStr = StringsUtils.getCode(clipString);//截取6位验证码
                        isClipboardChanged = true;
                    }
                }
            }
        });

    }

    /***
     * 验证码倒计时
     */
    private void countDown() {
        tv_getcode.setStart(context, 60000, 1000, new CountDownTextView.OnCountDownListener() {
            @Override
            public void onTick(long millisUntilFinished) {
                tv_getcode.setClickable(false);
                tv_getcode.setTextColor(getResources().getColor(R.color.color_999));
                long second = millisUntilFinished / 1000;
                tv_getcode.setText(AppTools.htmlText(String.valueOf(second), "验证码已发送(", ")s 可能会有延迟，请耐心等待", "#36B391"));
            }

            @Override
            public void onFinish() {
                tv_getcode.setClickable(true);
                tv_getcode.setTextColor(getResources().getColor(R.color.colorPrimary));
                tv_getcode.setText("重新发送验证码");
            }
        });
        tv_getcode.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (title.equals("短信验证")) {
                    //找回支付密码
                    presenter.getCode(context, "10", tel);
                } else {
                    presenter.getCode(context, "2", tel);
                }
            }
        });
    }

    /***
     * 验证码输入完成自动登录
     */
    public void inputComplete() {
//        code = phoneCode.getPhoneCode();
//        if (title.equals("登录")) {
//            presenter.login(context, 2, "", tel, code);
//        } else {
//            presenter.register(context, tel, code);
//        }
//        } else {
        //校验验证码并登录
//            presenter.login(context, 2, "", tel, code);
//            presenter.checkLogin(context, tel, code, openid, unionid, wxname, wxhead);
//        }
    }

    /***
     * 登录
     */
    @OnClick(R.id.login_sure)
    public void login() {
        code = phoneCode.getPhoneCode();
        if (title.equals("登录")) {
            presenter.login(context, 2, "", tel, code);
        } else {
            presenter.register(context, tel, code);
        }
    }

    /***
     * 重新获取验证码
     */
    @Override
    public void onGetCodeSuccess(String success) {
        countDown();
    }

    /***
     * 校验验证码登陆成功
     */
    @Override
    public void onLoginSuccess(UserBean userBean) {
//        if (userBean.isNew) {
//            //新用户,设置密码
//            Intent intent = new Intent(context, SetPwdActivity.class);
//            intent.putExtra("tel", tel);
//            intent.putExtra("code", code);
//            intent.putExtra("openid", openid);
//            intent.putExtra("unionid", unionid);
//            intent.putExtra("wxname", wxname);
//            intent.putExtra("wxhead", wxhead);
//            startActivity(intent);
//        } else {

        Map<String, Object> map = new HashMap<>();
        SPUtil.putString(Constant.USER_H5_KEY, GsonUtil.gsonString(map));
        UserUtils.saveUser(userBean);
        if (!false) {
            //旧用户,不用设置密码,跳到首页
            RxBus.get().post(RxBusCode.REFRESHUSER_POSITION, "");
            App.getInstance().finishTmpActivity();
        } else {
            //设置密码
            //新用户,设置密码
            Intent intent = new Intent(context, SetPwdActivity.class);
            //intent.putExtra("flagSetPassword", userBean.flagSetPassword);//设置密码
            startActivity(intent);
        }
//        }
    }

    /***
     * 找回支付密码,校验验证码成功
     */
    @Override
    public void onSuccess(boolean isSuc) {
        if (isSuc) {
            if (title.equals("注册")) {
                //新用户,设置密码
                Intent intent = new Intent(context, SetPwdActivity.class);
                intent.putExtra("tel", tel);
                intent.putExtra("code", code);
                intent.putExtra("openid", openid);
                intent.putExtra("unionid", unionid);
                intent.putExtra("wxname", wxname);
                intent.putExtra("wxhead", wxhead);
                startActivity(intent);
            } else if (title.equals("绑定手机号")) {//微信登陆
                if (isNew) {
                    //新用户,设置密码
                    Intent intent = new Intent(context, SetPwdActivity.class);
                    intent.putExtra("tel", tel);
                    intent.putExtra("code", code);
                    intent.putExtra("openid", openid);
                    intent.putExtra("unionid", unionid);
                    intent.putExtra("wxname", wxname);
                    intent.putExtra("wxhead", wxhead);
                    startActivity(intent);
                } else {
                    presenter.checkLogin(context, tel, code, openid, unionid, wxname, wxhead);
                }
            } else {
                Intent intent = new Intent(context, SetPayActivity.class);
                intent.putExtra("title", "设置支付密码");
                intent.putExtra("code", code);
                startActivity(intent);
            }
        } else {
            ToastUtil.showShort("验证码错误");
        }
    }

    @Override
    public <T> void onSuccess(T t, int type) {
        if (type == 9) {
            ToastFormat format = new ToastFormat(this);
            format.InitToast();
            format.setText("注册完成");
            format.setShowTime(3000);
            format.setGravity(Gravity.CENTER);
            format.show();
            register_suc = true;
            new Handler(Looper.myLooper()).postDelayed(() -> {
                App.getInstance().finishTmpActivity();
                startActivity(new Intent(context,LoginActivity.class));
            }, 3000);
        }
    }

    private boolean register_suc = false;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && register_suc) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onError(ThdException error) {
        ToastUtil.showShort(error.message);
    }

    @Subscribe(thread = EventThread.MAIN_THREAD, tags = {@Tag(RxBusCode.DIS_CODE)})
    public void dis(String param) {
        if (!isFinishing()) {
            finish();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!StringsUtils.isEmpty(codeStr) && isClipboardChanged) {
            phoneCode.clear();
            phoneCode.setCode(codeStr);
            isClipboardChanged = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != mSMSBroadcastReceiver) {
            unregisterReceiver(mSMSBroadcastReceiver);
        }
    }
}
